﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using CommerceOne.Binders;
using CommerceOne.Common;
using CommerceOne.Domains.Authentication;

namespace CommerceOne
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            var routeList = new List<RouteMappingItem>()
                                {
                                    new RouteMappingItem {
                                            PageName = "Default", 
                                            Url = "{controller}/{action}", 
                                            Defaults = new { controller = "Home", action = "Index" }
                                    },
                                    new RouteMappingItem { PageName = "Home", Url = "{pageNumber}", Defaults = new { controller = "Home", action = "Index" }, Constrains=new { pageNumber = @"\d{1,3}" } },
                                    new RouteMappingItem { 
                                        PageName = "ProductList", 
                                        Url = "category/{objectId}/{page}/{objectTitle}/", 
                                        Defaults = new { controller = "Product", action = "Index", page = UrlParameter.Optional }, 
                                        Constrains=new { page = @"\d{1,3}", objectId = @"\d{1,3}" } 
                                    },
                                    new RouteMappingItem { 
                                        PageName = "ProductDetail", 
                                        Url = "product/{objectId}/{objectTitle}", 
                                        Defaults = new { controller = "Product", action = "Detail" }, 
                                        Constrains=new { objectId = @"\d{1,3}" } 
                                    },
                                    new RouteMappingItem { 
                                        PageName = "Department", 
                                        Url = "{objectId}/Department/{page}", 
                                        Defaults = new { controller = "Department", action = "Index", page = UrlParameter.Optional }, 
                                        Constrains=new { page = @"\d{1,3}", objectId = @"\d{1,3}" } 
                                    },
                                    new RouteMappingItem { 
                                        PageName = "Brand", 
                                        Url = "{objectId}/Brand/{page}", 
                                        Defaults = new { controller = "Brand", action = "Index", page = UrlParameter.Optional }, 
                                        Constrains=new{ page = @"\d{1,3}", objectId = @"\d{1,3}" }
                                    },
                                     new RouteMappingItem { 
                                        PageName = "Registration", 
                                        Url = "Registration", 
                                        Defaults = new { controller = "Authentication", action = "Registration" }
                                    },
                                    new RouteMappingItem { 
                                        PageName = "Product", 
                                        Url = "{objectId}/Product", 
                                        Defaults = new { controller = "Product", action = "Detail" }, 
                                        Constrains=new { objectId = @"\d{1,3}" }
                                    },
                                    new RouteMappingItem { 
                                        PageName = "ProductComment", 
                                        Url = "Comments/{objectId}/{page}", 
                                        Defaults = new { controller = "Product", action = "Comments" }, 
                                        Constrains=new { objectId = @"\d{1,3}", page = @"\d{1,3}" }
                                    },
                                    new RouteMappingItem { 
                                        PageName = "AddToCart", 
                                        Url = "Add/{id}/{qty}/{returnUrl}", 
                                        Defaults = new { controller = "Cart", action = "AddToCart", returnUrl=UrlParameter.Optional, qty = 1 }, 
                                        Constrains=new { id = @"\d{1,3}", qty = @"\-*\d{1,3}" }
                                    },
                                    new RouteMappingItem { 
                                        PageName = "RemoveFromCart", 
                                        Url = "Remove/{id}/{returnUrl}", 
                                        Defaults = new { controller = "Cart", action = "Remove", returnUrl=UrlParameter.Optional }, 
                                        Constrains=new { id = @"\d{1,3}" }
                                    },
                                    new RouteMappingItem { PageName = "Cart", Url = "{controller}/Cart{action}", Defaults = new  { controller = "Cart", action = "Index" } },
                                    //new RouteMappingItem { PageName = "AddToCart", Url = "{controller}/Add{action}", Defaults = new { controller = "Cart", action = "AddToCart" }},
                                    new RouteMappingItem { PageName = "All-Brands", Url = "all-brands", Defaults = new { controller = "Brand", action = "AllBrand" } },
                                    new RouteMappingItem { PageName = "All-Categories", Url = "all-categories", Defaults = new { controller = "Department", action = "AllDepartment" } }
                                    
                                };


           // routes.MapRoute(
           //    "Home", // Route name
           //    "{pageNumber}", // URL with parameters
           //    new { controller = "Home", action = "Index", pageNumber = 1 }, // Parameter defaults
           //    new { pageNumber = @"\d{1,3}" }
           //);

           // routes.MapRoute(
           //    "Deparment", // Route name
           //    "{deparmentId}/Department/{pageNumber}", // URL with parameters
           //    new { controller = "Department", action = "Index", pageNumber = UrlParameter.Optional }, // Parameter defaults
           //    new { pageNumber = @"\d{1,3}", deparmentId = @"\d{1,3}" }
           //);

          //  routes.MapRoute(
          //    "Brand", // Route name
          //    "{brandId}/Brand/{pageNumber}", // URL with parameters
          //    new { controller = "Brand", action = "Index", pageNumber = UrlParameter.Optional }, // Parameter defaults
          //    new { pageNumber = @"\d{1,3}", brandId = @"\d{1,3}" }
          //);

         //   routes.MapRoute(
         //    "Product", // Route name
         //    "{productId}/Product", // URL with parameters
         //    new { controller = "Product", action = "Detail" }, // Parameter defaults
         //    new { productId = @"\d{1,3}" }
         //);

        //routes.MapRoute(
        //    "ProductComment", // Route name
        //    "Comments/{productId}/{page}", // URL with parameters
        //    new { controller = "Product", action = "Comments" }, // Parameter defaults
        //    new { productId = @"\d{1,3}", page = @"\d{1,3}" }
        //);

        //routes.MapRoute(
        //    "Cart", // Route name
        //    "{controller}/Cart{action}", // URL with parameters
        //    new { controller = "Cart", action = "Index" } // Parameter defaults
        //    );

        //routes.MapRoute(
        //    "AddToCart", // Route name
        //    "{controller}/{action}", // URL with parameters
        //    new { controller = "Cart", action = "AddToCart" } // Parameter defaults
        //    );

        //routes.MapRoute(
        //"RemoveCart", // Route name
        //"{controller}/Remove", // URL with parameters
        //new { controller = "Cart", action = "AddToCart" } // Parameter defaults
        //);

            //routes.MapRoute(
            //    "Default", // Route name
            //    "{controller}/{action}/{pageNumber}", // URL with parameters
            //    new { controller = "Home", action = "Index", pageNumber = UrlParameter.Optional }, // Parameter defaults
            //    new { pageNumber = @"\d{1,3}" }
            //);

            foreach (var routeItem in routeList)
            {
                UrlBuilderService.Instance.Add(routeItem.PageName, routeItem.Url);
                routes.MapRoute(routeItem.PageName, routeItem.Url, routeItem.Defaults, routeItem.Constrains);
            }
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder());

            //WidgetConfiguration widgetConfiguration = WidgetConfiguration.GetWidgetConfiguration(new ConfigurationManagerWrapper());
            //widgetConfiguration.Context = new HttpContextWrapper(HttpContext.Current);
            //Application["WidgetConfiguration"] = widgetConfiguration;
            //Application["WidgetInstances"] = widgetConfiguration.GetWidgetInstanceDictionary();

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (Request.IsAuthenticated)
            {
                //get the username which we previously set in
                //forms authentication ticket in our login1_authenticate event
                string userName = HttpContext.Current.User.Identity.Name;
                string userData = ((FormsIdentity) HttpContext.Current.User.Identity).Ticket.UserData;
                string[] data = userData.Split(new char[] {'|'});
                int id = Convert.ToInt32(data[0]);
                string role = data[1];

                //build a custom identity and custom principal object based on this username
                var identity = new CommerceOneIdentity(id, userName, role);
                var principal = new CommerceOnePrincipal(identity);

                //set the principal to the current context
                HttpContext.Current.User = principal;
            }
        }
    }
}